//
//  ZHAvatarView.m
//  Pod
//
//  Created by green on 24/10/2017.
//  Copyright © 2017 zhihan. All rights reserved.
//

#import "ZHAvatarView.h"
#import "ZHAvatarUtils.h"
#import <BCWebImageKit/BCWebImageManager.h>
#import <BCFoundation/BCFoundationUtils.h>
#import <BCFoundation/UIColor+BCHelper.h>
#import <BCFoundation/NSString+BCHelper.h>
#import <BCFoundation/NSURL+BCHelper.h>
#import <BCUIKit/UIView+ZHHelper.h>

@interface ZHAvatarView ()
@property (strong, nonatomic, readwrite) UIImageView    *baseImg;
@property (strong, nonatomic, readwrite) UILabel        *placeholderLb;
@property (strong, nonatomic) NSString  *avatar;//头像URL
@property (strong, nonatomic) UIImage   *avatarImg;//头像img
/** 默认头像image */
@property (nonatomic, strong) UIImage   *defaultImg;
@property (strong, nonatomic) NSString  *name;
@property (weak, nonatomic) id<BCWebImageOperation>     downloadOperation;

@end

@implementation ZHAvatarView
//MARK: - system
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _suffixCount = 2;
        _needRandomColor = YES;
        _showCorner = NO;
        _showCorner = YES;
        _showBorder = NO;
        [self loadBaseImg];
        [self loadPlaceholderLb];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _suffixCount = 2;
        _needRandomColor = YES;
        _showCorner = NO;
        _showCorner = YES;
        _showBorder = NO;
        [self loadBaseImg];
        [self loadPlaceholderLb];
    }
    return self;
}
-(void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor = [UIColor whiteColor];
    _suffixCount = 2;
    _needRandomColor = YES;
    _showCorner = NO;
    _showCorner = YES;
    _showBorder = NO;
    [self loadBaseImg];
    [self loadPlaceholderLb];
}
- (void)dealloc
{
    BCLogDealloc();
}

//MARK: - setter
-(void)setImgFrame:(CGRect)imgFrame
{
    _imgFrame = imgFrame;
    if(_baseImg){
        _baseImg.frame = imgFrame;
    }
}

-(void)setTitleFrame:(CGRect)titleFrame
{
    _titleFrame = titleFrame;
    if(_placeholderLb){
        _placeholderLb.frame = titleFrame;
    }
}
-(UIColor *)defaultBgColor {
    if (!_defaultBgColor) {
        return [UIColor grayColor];
    }
    return _defaultBgColor;
}

-(UIColor *)borderColor {
    if (!_borderColor) {
        _borderColor = [UIColor whiteColor];
    }
    return _borderColor;
}

//MARK: - praivte
- (void)loadBaseImg
{
    if(!_baseImg){
        _baseImg = [[UIImageView alloc] initWithFrame:self.bounds];
        _baseImg.clipsToBounds = YES;
        //        _baseImg.backgroundColor = [UIColor clearColor];
    }
    if(!_baseImg.superview){
        [self addSubview:_baseImg];
    }
}

- (void)loadPlaceholderLb
{
    if (!_placeholderLb){
        _placeholderLb = [[UILabel alloc] init];
        _placeholderLb.numberOfLines = 1;
        _placeholderLb.lineBreakMode = NSLineBreakByTruncatingTail;
        _placeholderLb.textColor = [UIColor whiteColor];
        _placeholderLb.textAlignment = NSTextAlignmentCenter;
        _placeholderLb.frame = self.bounds;
    }
    if(!_placeholderLb.superview){
        [self addSubview:_placeholderLb];
    }
}

//MARK: - layout

- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.showCorner) {
        self.layer.cornerRadius = self.bc_width/2.0;
    }
    //    self.placeholderLb.adjustsFontSizeToFitWidth = YES;
    
    // reset img
    //    CGFloat borderWidth = [self imgWhiteBorderWidth];
    if (self.imgFrame.size.width > 0) {
        self.baseImg.frame = self.imgFrame;
    } else {
        //        self.baseImg.frame = CGRectMake(borderWidth, borderWidth, self.bc_width - 2 * borderWidth, self.bc_width - 2 * borderWidth);
        self.baseImg.frame = CGRectMake(0, 0, self.bc_width, self.bc_width);
    }
    if (self.showCorner) {
        self.baseImg.layer.cornerRadius = (self.baseImg.bc_width)/2.0;
    }
    
    // reset label
    NSInteger fontSize = [ZHAvatarUtils zh_avatarFontSize:self.bc_size withLength:self.suffixCount];
    self.placeholderLb.font = [UIFont systemFontOfSize:fontSize];
    if (self.titleFrame.size.width > 0) {
        self.placeholderLb.frame = self.titleFrame;
    }
    else {
        self.placeholderLb.frame = self.baseImg.frame;
        //        [self.placeholderLb sizeToFit];
        //        self.placeholderLb.bc_origin = CGPointMake((self.bc_width - self.placeholderLb.bc_width)/2, (self.bc_height - self.placeholderLb.bc_height)/2);
    }
}

- (void)showImgBorder
{
    if (self.showBorder) {
        CGFloat borderWidth = [self imgWhiteBorderWidth];
        self.layer.borderColor = self.borderColor.CGColor;
        self.layer.borderWidth = borderWidth;
    }
}

- (void)clearImgBorder
{
    self.layer.borderColor = nil;
    self.layer.borderWidth = 0;
}

//MARK: - 配置头像

- (void)configAvatar:(NSString *)avatar andName:(NSString *)name {
    _avatar = avatar;
    _name = name;
    [self.downloadOperation cancel];
    if (avatar.length<=0 && name.length<=0) {
        // 头像和名称都没有，则显示匿名
        [self showAnonymous];
        return;
    }
    
    if (name.length > 0) {
        //优先展示 name
        [self showName:name];
    }
    else{
        //name 为空
        self.placeholderLb.text = nil;
    }
    if(avatar.length>0){//头像URL正确
        self.baseImg.image = nil;
        BCWeakObj(self);
        self.downloadOperation = [BCWebImageManager loadImageWithURL:[NSURL bc_URLWithString:avatar]  options:(BCWebImageHighPriority | BCWebImageAllowInvalidSSLCertificates) progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BCImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            BCStrongObj(self);
            if (avatar.length>0 && image) {
                //下载成功，移除 name、还原背景图片
                [self showBaseImg:image];
            }
        }];
    }
    else{
        self.baseImg.image = nil;
        //        self.baseImg.backgroundColor = [ZHAvatarUtils zh_randomColorWithName:name];
    }
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

-(void)configAvatar:(NSString *)avatar andDefaultImg:(UIImage *)defaultImg {
    _avatar = avatar;
    _defaultImg = defaultImg;
    [self.downloadOperation cancel];
    if (avatar.length<=0 && !self.defaultImg) {
        // 头像和默认图都没有，则显示匿名
        [self showAnonymous];
        return;
    }
    if (self.defaultImg) {
        //优先展示 默认图
        [self showBaseImg:self.defaultImg];
    }
    else{
        //默认图 nil
    }
    if(avatar.length>0){//头像URL正确
        BCWeakObj(self);
        self.downloadOperation = [BCWebImageManager loadImageWithURL:[NSURL URLWithString:avatar] options:(BCWebImageHighPriority | BCWebImageAllowInvalidSSLCertificates) progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BCImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            BCStrongObj(self);
            if (avatar.length>0 && image) {
                //下载成功，移除 name、还原背景图片
                [self showBaseImg:image];
            }
        }];
    }
    else {
        //没有头像URL
    }
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)configAvatarImg:(UIImage *)avatarImg andName:(NSString *)name
{
    _avatarImg = avatarImg;
    _name = name;
    [self.downloadOperation cancel];
    if(avatarImg) {
        // 头像 img 正确，清除其他，直接设置 img
        [self showBaseImg:avatarImg];
    }
    else {
        self.baseImg.image = nil;
        // 没有头像
        if(name.length>0){
            // 有 name 则显示 name
            [self showName:name];
        }
        else{
            // 头像和名称都没有，则显示匿名
            [self showAnonymous];
        }
    }
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)clearAvatar
{
    [self.downloadOperation cancel];
    self.placeholderLb.text = nil;
    self.baseImg.image = nil;
    //    self.baseImg.backgroundColor = [UIColor clearColor];
    [self clearImgBorder];
}

//- (void)setHideCorner:(BOOL)hideCorner
//{
//    self.placeholderLb.text = nil;
//    self.baseImg.image = nil;
//    self.baseImg.backgroundColor = [UIColor clearColor];
//    [self clearImgBorder];
//}


//MARK: - private
- (void)showAnonymous {
    //    [self showName:BCLOC(@"匿")];
    self.baseImg.backgroundColor = self.defaultBgColor;
}

- (void)showName:(NSString *)name
{
    self.baseImg.image = nil;
    name = [NSString bc_trimString:name];
    if (name.length > 0) {
        NSInteger suffixCountTmp = self.suffixCount;
        if (name.length < self.suffixCount) {
            //截取的位数超过名称长度
            suffixCountTmp = name.length;
        }
        NSString *showName = [name substringWithRange:NSMakeRange(name.length-suffixCountTmp, suffixCountTmp)];
        self.placeholderLb.text = [showName uppercaseString];
        if(self.needRandomColor){
            self.baseImg.backgroundColor = [ZHAvatarUtils zh_randomColorWithName:showName];
        }
    }
    [self showImgBorder];
}

- (void)showNum:(NSInteger)num {
    [self clearImgBorder];
    NSString *numStr = [NSString stringWithFormat:@"+%ld", (long)num];
    self.placeholderLb.text = numStr;
    self.placeholderLb.textColor = [UIColor blackColor];
    
    self.baseImg.image = nil;
    self.baseImg.backgroundColor = [UIColor whiteColor];
}

- (void)showBaseImg:(UIImage *)img
{
    [self showImgBorder];
    self.baseImg.image = img;
    self.baseImg.contentMode = UIViewContentModeScaleAspectFill;
    self.baseImg.backgroundColor = [UIColor clearColor];
    self.placeholderLb.text = nil;
}

//MARK: - helper
- (CGFloat )imgWhiteBorderWidth {
    if (!self.showBorder) {//是否隐藏边框
        return 0;
    }
    if (self.borderWidth>0) {
        return self.borderWidth;
    }
    CGFloat width = self.bc_width;
    if (width < 25) {
        return 1.0;
    }
    else if (width > 60) {
        return 3;
    }
    else {
        return 1.5;
    }
}

@end

